<route lang="jsonc" type="home">{
  "layout": "tabbar",
  "style": {
    "navigationStyle": "custom"
  }
}</route>

<script lang="ts" setup>
import { useOemStore } from '@/store/oem'
import { calc, plus, div, sub, fmt } from 'a-calc'
// import Select from './components/Select.vue'
import SelectMonth from './components/SelectMonth.vue'
import Result from './components/Result.vue'

import colorConvert from "color-convert"
uni.hideTabBar()
let amount = ref()

// const selectHandle = (val) => {
//   console.log("月收入10W以上选项", val)
// }

const oemStore = useOemStore()

onMounted(async () => {
  const data = await oemStore.getQueryOemCode2();
  document.title = data.oemName
  // 动态修改网页icon
  document.querySelectorAll("link[rel*='icon']").forEach(item => {
    if (item instanceof HTMLLinkElement) {
      item.href = data.icoFile[0].url;
    }
  })
  document.querySelectorAll(".sar-portal").forEach(item => {
    if (item instanceof HTMLElement) {
      item.style.setProperty('--sar-blue', data.themeColor)
      item.style.setProperty('--sar-blue-rgb', colorConvert.hex.rgb(data.themeColor).join(','))
    }

  })
  const uniPageBody = document.querySelector("uni-page-body");
  if (uniPageBody instanceof HTMLElement) {
    uniPageBody.style.setProperty('--sar-blue', data.themeColor)
    uniPageBody.style.setProperty('--sar-blue-rgb', colorConvert.hex.rgb(data.themeColor).join(','))
  }

})

let monthList = ref([])
const selectMonthChangeHandle = (val) => {
  // console.log("xx元/月", val)
  monthList.value = val
}

const inputHandle = (val) => {
  if (val >= 5000000) {
    uni.showModal({
      content: '您好！您经营的业务额度已超过500万，需要注册公司经营！',
      confirmText: '知道了',
      showCancel: false,
    })
  }
}

let taxTable = [
  { yearAmount: [0, 36000], tax: 0.03, taxAmount: 0 },
  { yearAmount: [36000, 144000], tax: 0.1, taxAmount: 2520 },
  { yearAmount: [144000, 300000], tax: 0.2, taxAmount: 16920 },
  { yearAmount: [300000, 420000], tax: 0.25, taxAmount: 31920 },
  { yearAmount: [420000, 660000], tax: 0.3, taxAmount: 52920 },
  { yearAmount: [660000, 960000], tax: 0.35, taxAmount: 85920 },
  { yearAmount: [960000, Infinity], tax: 0.45, taxAmount: 181920 },
]

export interface TaxItem {
  // 月份
  month: string,
  // 税前
  preTax: number | string,
  // 预计扣除
  deduct: number | string,
  // 税后
  afterTax: number | string,
  // 实际税负
  tax: number | string
}
const resultData = computed(() => {
  let calcList = [] as TaxItem[]
  monthList.value.map((preTax, index) => {
    // 本年连续获得收入的月份数
    const reverseMonthList = [...monthList.value].slice(0, index + 1).reverse()
    const monthIndex = reverseMonthList.findIndex(amount => !amount)
    // 本年连续获得收入的月份数
    const consecutiveMonthsCount = monthIndex === -1 ? reverseMonthList.length : monthIndex
    // 连续月累计收入
    const monthlyAccumulatedRevenue = [...reverseMonthList].slice(0, consecutiveMonthsCount).reduce((acc, cur) => plus(acc, cur), 0)
    // 年累计已纳税额
    //  1.反转数组
    const reverseList = [...calcList].reverse()
    //  2.找出连续已纳税额的索引
    let lianxuIndex = reverseList.findIndex(item => !item.preTax)
    //  3.获取连续已纳税额
    let yearTaxAmount = reverseList.slice(0, lianxuIndex === -1 ? reverseList.length : lianxuIndex).reduce((acc, cur) => plus(acc, cur.deduct || 0), 0)
    // 累计预扣预缴应纳税所得额
    const value = calc(`${monthlyAccumulatedRevenue} * 0.8 - 5000 * ${consecutiveMonthsCount} | !n`)
    // 根据月收入在taxTable中查找对应的税率和速算扣除数
    const { tax = 0, taxAmount = 0 } = taxTable.find(item => item.yearAmount[0] < value && value <= item.yearAmount[1]) || {}
    // 计算预扣税
    let deduct = parseFloat(calc(value * tax - taxAmount - yearTaxAmount, { _fmt: "=2 ~6" }))
    deduct = deduct < 0 ? 0 : deduct

    console.log(`----------------${index + 1}月-----------------开始----`)
    console.log("连续月累计收入", monthlyAccumulatedRevenue)
    console.log("本年连续获得收入的月份数", consecutiveMonthsCount)
    console.log("预扣率", tax)
    console.log("速算扣除数", taxAmount)
    console.log("年累计已纳税额", yearTaxAmount, reverseList.slice(0, lianxuIndex === -1 ? reverseList.length : lianxuIndex))
    console.log("预扣税", deduct, typeof preTax)
    console.log(`----------------${index + 1}月-----------------结束----`)

    calcList.push({
      month: index + 1 + "月",
      preTax,
      deduct: preTax === "" ? preTax : deduct,
      afterTax: preTax === "" ? preTax : calc(`${preTax} - ${deduct} | !n`),
      tax: preTax === "" ? preTax : calc(`${deduct} / ${preTax} * 100 | !n`, { _fmt: "=2 ~6" })
    })
  })
  return calcList
})

const showTaxResult = computed(() => {
  return monthList.value.reduce((acc, cur) => plus(acc, cur || 0), 0) > 0
})  
</script>

<template>
  <view class="home h-full overflow-y-auto bg-white">
    <view class="home-bg flex justify-center box-border">
      <!-- <view :style="`background: ${oemStore.oemInfo.themeColor};height: 80rpx`"> -->
      <image :src="oemStore.oemInfo.logoFile[0]?.url" style="height: 80rpx; width: 50%"
        :style="`background: ${oemStore.oemInfo.themeColor}`" />
      <!-- </view> -->
    </view>
    <view class="px-20rpx">
      <view class="container p-20rpx box-border">
        <navigator url="/pages/tax/index" open-type="navigate" hover-class="navigator-hover">
          <sar-button type="pale">个税新政依据查看</sar-button>
        </navigator>
        <view class="mt-20rpx flex items-center">
          <text class="font-size-28rpx">连续劳务月收入</text>
          <view class="ml-40rpx flex-1 bg-#f2f3f7 rd-8rpx">
            <sar-input v-model="amount" placeholder="请输入金额" borderless clearable show-clear-only-focus
              inputmode="numeric" type="digit" root-style="text-align: center;" placeholder-style="text-align: center;"
              @input="inputHandle">
              <template #append>
                <text class="font-size-28rpx">元</text>
              </template>
            </sar-input>
          </view>
        </view>
        <!-- <view class="mt-20rpx">
          <Select :radioValue="6" @change="selectHandle" />
        </view> -->
        <view class="mt-40rpx">
          <SelectMonth :amount="amount" @change="selectMonthChangeHandle" />
        </view>
        <view class="mt-20rpx" v-if="showTaxResult">
          <Result :data="resultData" />
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.home-bg {
  height: 576rpx;
  background: url(https://calc.jiehaohuo.com/assets/header-bg-CFgVXZRN.png) no-repeat top center;
  background-size: 100% 100%;
}

.container {
  margin-top: -259rpx;
  background: #fff;
  border-radius: 1rem;
  overflow: hidden;
  min-height: 70vh;
}
</style>